#ifndef OA_CORE_KERNEL_H
#define OA_CORE_KERNEL_H

#include "util/std.h"
#include "util/tbb.h"
#include "util/boost.h"
#include "util/osg.h"
#include "core/event.h"

namespace core {
	class Task:
		virtual public osg::Referenced
	{
	public:
		virtual void tick() = 0;
	};
	
	class Kernel:
		public osg::Referenced
	{
	public:
		struct StopEvent: public Event {};

		Kernel();
		~Kernel();

		void addTask(Task* t, bool repeating = true, bool parallel = true);
		void removeTask(Task* t);

		void run();
		void onStop();

		StopEvent mStop;

	protected:
		typedef osg::ref_ptr<Task> TaskPtr;
		typedef std::pair<bool, TaskPtr> TaskPair;
		typedef std::list<TaskPair> TaskList;
		typedef TaskList::iterator TaskIterator;

		class RootTask: public tbb::task {
		public:
			RootTask(Kernel* parent);

			tbb::task* execute();

		private:
			Kernel* mParent;
		};

		TaskList mTasks;
		TaskList mParallelTasks;
		bool mRunning;
		RootTask* mRootTask;

		typedef tbb::queuing_mutex Mutex;
		typedef Mutex::scoped_lock ScopedLock;
		Mutex mMutex;

		friend class RootTask;
	};
}

#endif
